package tms.view;

import java.awt.BorderLayout;

import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JButton;

import tms.Cache;
import tms.controler.AccountController;
import tms.controler.ContactInfoController;
import tms.model.Account;
import tms.model.Booking;
import tms.service.ServiceHandler;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormSpecs;
import com.jgoodies.forms.layout.RowSpec;

public class ContactInfoView extends JPanel {

    static final long serialVersionUID = 1L;

    private ContactInfoPanel pnlContactInfo;
    private ExtraInfoPanel pnlExtraRegisterInfo;
    private AccountController accountController;
    private JCheckBox chckbxBookerIsPassenger;
    private JTextField txtFullNameN2;
    private JTextField txtMobileNumN2;
    private JTextField txtEmailN2;

    private JCheckBox ckbCreateAccount;

    private JTextField txtPassNum;

    private JButton btnContinue;

    private static Account guest;

    private ContactInfoController contactInfoController;

    public ContactInfoView(ContactInfoController controller) {

        final Account currentUser = Cache.currentUser;
        this.contactInfoController = controller;
        accountController = new AccountController();
        setLayout(new BorderLayout());
        JPanel pnlBookingContactInfo = new JPanel();
        add(pnlBookingContactInfo, BorderLayout.CENTER);
        pnlBookingContactInfo.setLayout(new FormLayout(new ColumnSpec[] {
                FormSpecs.UNRELATED_GAP_COLSPEC,
                FormSpecs.UNRELATED_GAP_COLSPEC,
                ColumnSpec.decode("max(74dlu;default)"),
                FormSpecs.DEFAULT_COLSPEC,
                ColumnSpec.decode("max(73dlu;pref)"),
                FormSpecs.GROWING_BUTTON_COLSPEC},
                new RowSpec[] {FormSpecs.UNRELATED_GAP_ROWSPEC,
                        FormSpecs.DEFAULT_ROWSPEC,
                        FormSpecs.LINE_GAP_ROWSPEC,
                        FormSpecs.DEFAULT_ROWSPEC,
                        FormSpecs.UNRELATED_GAP_ROWSPEC,
                        FormSpecs.DEFAULT_ROWSPEC,
                        FormSpecs.RELATED_GAP_ROWSPEC,
                        FormSpecs.DEFAULT_ROWSPEC,
                        FormSpecs.RELATED_GAP_ROWSPEC,
                        FormSpecs.DEFAULT_ROWSPEC,
                        FormSpecs.UNRELATED_GAP_ROWSPEC,
                        FormSpecs.DEFAULT_ROWSPEC}));
        pnlBookingContactInfo.add(Tools.createLabel("Primary Reservation Contact Information",
                        Tools.TAHOMA_BOLD_14), "2, 2, 5, 1, fill, fill");

        pnlContactInfo = new ContactInfoPanel();
        pnlBookingContactInfo.add(pnlContactInfo, "3, 4, 4, 1, fill, fill");

        final JPanel pnlPassN2 = new JPanel();
        pnlPassN2.setLayout(new FormLayout(new ColumnSpec[] {
                ColumnSpec.decode("max(74dlu;default)"),
                FormSpecs.RELATED_GAP_COLSPEC, ColumnSpec.decode("74dlu"),
                FormSpecs.GROWING_BUTTON_COLSPEC, }, new RowSpec[] {
                FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
                FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
                FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
                FormSpecs.DEFAULT_ROWSPEC, FormSpecs.RELATED_GAP_ROWSPEC,
                FormSpecs.DEFAULT_ROWSPEC, }));
        pnlPassN2.setVisible(false);

        ckbCreateAccount = Tools.createCheckBox("Create account from contact info");
        pnlBookingContactInfo.add(ckbCreateAccount, "5, 6");
        if (Cache.currentUser != null) {
            ckbCreateAccount.setVisible(false);
        } else {
            ckbCreateAccount.setVisible(true);
        }
        ckbCreateAccount.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (ckbCreateAccount.isSelected()) {
                    pnlExtraRegisterInfo.setVisible(true);
                } else {
                    pnlExtraRegisterInfo.setVisible(false);
                }
            }
        });
        pnlBookingContactInfo.add(pnlPassN2, "3, 8, 4, 1, fill, fill");

        pnlPassN2.add(Tools.createLabel("Information of booker",
                Tools.TAHOMA_BOLD_12), "1, 1, 3, 1, fill, fill");

//      pnlPassN2.add(Tools.createLabel("Passenger number:"), "1, 3");
//      txtPassNum = Tools.createPasswordField();
//      pnlPassN2.add(txtPassNum, "3, 3");

        pnlPassN2.add(Tools.createLabel("Name: "), "1, 5");
        txtFullNameN2 = Tools.createTextField("");
        pnlPassN2.add(txtFullNameN2, "3, 5");

        pnlPassN2.add(Tools.createLabel("Email: "), "1, 7");
        txtEmailN2 = Tools.createTextField("");
        pnlPassN2.add(txtEmailN2, "3, 7");

        pnlPassN2.add(Tools.createLabel("Mobile number: "), "1, 9");
        txtMobileNumN2 = Tools.createTextField("");
        pnlPassN2.add(txtMobileNumN2, "3, 9");

        chckbxBookerIsPassenger = Tools.createCheckBox("Booker is passenger");
        chckbxBookerIsPassenger.setSelected(true);
        pnlBookingContactInfo.add(chckbxBookerIsPassenger, "3, 6");
        chckbxBookerIsPassenger.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                if (chckbxBookerIsPassenger.isSelected()) {
                    pnlPassN2.setVisible(false);
                } else {
                    pnlPassN2.setVisible(true);
                }

            }
        });

        pnlExtraRegisterInfo = new ExtraInfoPanel();
        pnlBookingContactInfo.add(pnlExtraRegisterInfo,
                "3, 10, 4, 1, fill, top");
        pnlExtraRegisterInfo.setVisible(false);

        btnContinue = Tools.createButton("Continue");
        btnContinue.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                Booking tempDepartTicket = contactInfoController.getBookingSummaryController().getDepatureTicket();
                Booking tempReturnTicket = contactInfoController.getBookingSummaryController().getReturnTicket();
                boolean goOn = true;
                if (ckbCreateAccount.isSelected()) {

                    if (pnlContactInfo.checkValidInput()
                            && pnlExtraRegisterInfo.checkValidPassword()) {


                        String pw = pnlExtraRegisterInfo.getPassword();
                        String title = pnlContactInfo.getTitle();
                        String fname = pnlContactInfo.getFname();
                        String lname = pnlContactInfo.getLname();
                        String email = pnlContactInfo.getEmail();
                        String phone = pnlContactInfo.getPhoneNumber();
                        String address = pnlContactInfo.getAddress();
                        String country = pnlContactInfo.getCountry();
                        String passportNumber = pnlExtraRegisterInfo.getPassportNumber();
                        String issuingCountry = pnlExtraRegisterInfo.getIssuingCountry();

                        boolean res = accountController.createOrUpdate(null, title, fname, lname, email,
                                "personalID", address, phone, pw, "username", "city", "province", country,
                                passportNumber, pnlContactInfo.getDOB(), issuingCountry);
                        if (res) {
                        	guest = ServiceHandler.getFirstAccount("email like '" + email +"' AND password like '"+ pw +"'");
                            JOptionPane.showMessageDialog(null, "Register success");
                        } else {
                            JOptionPane.showMessageDialog(null, "Fail to register");
                        }
                    } else {
                        JOptionPane.showMessageDialog(null,
                                "Please input information of passenger to create account");
                        goOn = false;
                    }
                }
                if (!chckbxBookerIsPassenger.isSelected()) {
//                    String accountNumber = txtPassNum.getText();
//                    if (!accountNumber.isEmpty()) {
//                        Account passenger = ServiceHandler.getFirstAccount("AccountNumber = '" + accountNumber + "'");
//                        if (passenger != null) {
//                            contactInfoController.setAccountNmuber(accountNumber);
//                        } else {
//                            JOptionPane.showMessageDialog(null, "Please input correct passenger number");
//                            goOn = false;
//                        }
//                    }
                    String fullNameN2 = txtFullNameN2.getText();
                    String emailN2 = txtEmailN2.getText();
                    String phoneN2 = txtMobileNumN2.getText();
                    if (checkValidInputBooker(fullNameN2,  emailN2,  phoneN2)) {
                         //insert Booker into BookingTicket
                        tempDepartTicket.setBookingPersonEmail(emailN2);
                        tempDepartTicket.setBookingPersonName(fullNameN2);
                        tempDepartTicket.setBookingPersonPhone(phoneN2);
                        contactInfoController.getBookingSummaryController().setDepatureTicket(tempDepartTicket);

                        if (tempReturnTicket != null) {
                            tempReturnTicket.setBookingPersonEmail(emailN2);
                            tempReturnTicket.setBookingPersonName(fullNameN2);
                            tempReturnTicket.setBookingPersonPhone(phoneN2);
                            contactInfoController.getBookingSummaryController().setReturnTicket(tempReturnTicket);
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "Please input information of booker");
                        goOn = false;
                    }
                }
                if (currentUser != null) {
                    //add account user into BookingTicket (with the case is user)
                    int idUser = currentUser.getId();
                    tempDepartTicket.setIdBookingAccount(idUser);
                    contactInfoController.getBookingSummaryController().setDepatureTicket(tempDepartTicket);

                    if (tempReturnTicket != null) {
                        tempReturnTicket.setIdBookingAccount(idUser);
                        contactInfoController.getBookingSummaryController().setReturnTicket(tempReturnTicket);
                    }
                } else {
                    //add information of passenger into BookingTicket (with the case is guest)

                    String fname = pnlContactInfo.getFname();
                    String lname = pnlContactInfo.getLname();
                    String passengerName = fname + lname;

                    String passengerEmail = pnlContactInfo.getEmail();
                    String passengerPhone = pnlContactInfo.getPhoneNumber();
                    String passengerPassport = pnlExtraRegisterInfo.getPassportNumber();


                    if (fname.trim().isEmpty() || lname.trim().isEmpty() || !ContactInfoPanel.isValidEmailAddress(passengerEmail)
                            || passengerPhone.trim().isEmpty()) {
                        goOn = false;
                        JOptionPane.showMessageDialog(null, "Please input information of passenger if the guest");
                    } else {
                        guest = new Account();
                        guest.setFirstName(fname);
                        guest.setLastName(lname);
                        guest.setEmail(passengerEmail);
                        guest.setPhone(passengerPhone);

//                        String pw = pnlExtraRegisterInfo.getPassword();
//                        String title = pnlContactInfo.getTitle();
//                        String fname = pnlContactInfo.getFname();
//                        String lname = pnlContactInfo.getLname();
//                        String email = pnlContactInfo.getEmail();
//                        String phone = pnlContactInfo.getPhoneNumber();
//                        String address = pnlContactInfo.getAddress();
//                        String country = pnlContactInfo.getCountry();
//                        String passportNumber = pnlExtraRegisterInfo.getPassportNumber();
//                        String issuingCountry = pnlExtraRegisterInfo.getIssuingCountry();
//
//                        boolean res = accountController.createOrUpdate(null, title, fname, lname, email,
//                                "personalID", address, phone, pw, "username", "city", "province", country,
//                                passportNumber, pnlContactInfo.getDOB(), issuingCountry);

                        guest.setAddress(pnlContactInfo.getAddress());
                        guest.setTitle(pnlContactInfo.getTitle());
                        guest.setBirthDate(pnlContactInfo.getDOB());
                        guest.setCountry(pnlContactInfo.getCountry());

                        tempDepartTicket.setPassengerName(passengerName);
                        tempDepartTicket.setPassengerEmail(passengerEmail);
                        tempDepartTicket.setPassengerPhone(passengerPhone);
                        tempDepartTicket.setPassengerPassport(passengerPassport);
                        contactInfoController.getBookingSummaryController().setDepatureTicket(tempDepartTicket);

                        if (tempReturnTicket != null) {
                            tempReturnTicket.setPassengerName(passengerName);
                            tempReturnTicket.setPassengerEmail(passengerEmail);
                            tempReturnTicket.setPassengerPhone(passengerPhone);
                            tempReturnTicket.setPassengerPassport(passengerPassport);
                            contactInfoController.getBookingSummaryController().setReturnTicket(tempReturnTicket);
                        }

                    }
                }

                if (goOn == true) {
                    contactInfoController.moveToAddonView();
                }
            }
        });
        pnlBookingContactInfo.add(btnContinue, "3, 12, left, fill");
        if (currentUser != null) {
            Account acc = Cache.currentUser;
            pnlContactInfo.setTitle(acc.getTitle());
            pnlContactInfo.setFname(acc.getFirstName());
            pnlContactInfo.setLname(acc.getLastName());
            pnlContactInfo.setDOB(acc.getBirthDate());
            pnlContactInfo.setAddress(acc.getAddress());
            pnlContactInfo.setPhoneNumber(acc.getPhone());
            pnlContactInfo.setEmail(acc.getEmail());
            pnlContactInfo.setCountry(acc.getCountry());
        }
    }

    public void addBookingSummaryPanel(SummaryPanel pnl) {
        this.add(pnl, BorderLayout.NORTH);
    }

    private boolean checkValidInputBooker(String fullNameN2, String emailN2, String phoneN2) {
        return isValidAccountInfo(fullNameN2, phoneN2) && ContactInfoPanel.isValidEmailAddress(emailN2);
    }

    private boolean isValidAccountInfo(String fullNameN2, String phoneN2) {

        return !fullNameN2.trim().isEmpty() && !phoneN2.trim().isEmpty();
    }

    public static Account getGuest() {
        return guest;
    }

}
